package customer

import (
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/config"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/entity"
	"gitee.com/baal1990/gitee.com/baal1990/cmd/server/app/global"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/crypto"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/model"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
)

// GetMsgCode 获取短信验证码
func GetMsgCode(c *gin.Context) {
	req := entity.ReqMsgCode{}
	if err := c.ShouldBindQuery(&req); err != nil {
		global.Log.Error("GetMsgCode ShouldBindQuery fail", zap.Any("err", err))
		c.JSON(http.StatusOK, model.Fail("参数错误"))
		return
	}
	// 解密手机号码
	cryptoInst, ok := global.Crypto.Asymmetric[crypto.CryptoSM2]
	if !ok {
		global.Log.Error("GetMsgCode invalid crypto", zap.Any("type", crypto.CryptoSM2))
		c.JSON(http.StatusOK, model.Fail("内部错误"))
		return
	}
	mobileByte, err := cryptoInst.DecryptWithBase64(req.Mobile, global.ASymmetricPrivateKey)
	if err != nil {
		global.Log.Error("GetMsgCode invalid sm2.Decrypt", zap.Any("err", err))
		c.JSON(http.StatusOK, model.Fail("内部错误"))
		return
	}
	req.Mobile = string(mobileByte)
	code, err := global.MsgCodeGenerator.Gen(req.Mobile)
	if err != nil {
		global.Log.Error("GetMsgCode MsgCodeGenerator fail", zap.Any("err", err))
		c.JSON(http.StatusOK, model.Fail("内部错误"))
		return
	}
	err = global.Sms.SendMsg([]string{req.Mobile}, config.SmsSetting().Code.Template, config.SmsSetting().Code.Sign, code)
	if err != nil {
		global.Log.Error("GetMsgCode SendMsg fail", zap.Any("err", err))
		c.JSON(http.StatusOK, model.Fail("内部错误"))
		return
	}
	c.JSON(http.StatusOK, model.Success("操作成功"))
}
